import * as API_Upload from '../../utils/fileUpload'
import * as API_RichEditor from '../../api/richEditor'

function item(type,value,fontArray,fontSuffix,colorArray,colorSuffix,fontWeight,weightState,fontCenter,centerState,videoThumb){
  this.type = type
  this.value = value
  this.fontArray = fontArray
  this.fontSuffix = fontSuffix
  this.colorArray = colorArray
  this.colorSuffix = colorSuffix
  this.fontWeight = fontWeight
  this.weightState = weightState
  this.fontCenter = fontCenter
  this.centerState = centerState
  this.videoThumb = videoThumb
}
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    supportType: {
      type: Object,
      value: {
        text: {
          name: '文字',
          type: 'text',
          isSupport: true,
          maxNum: 120
        },
        image: {
          name: '大图',
          type: 'bigImg',
          isSupport: true,
          supportSource: ['album', 'camera'],
          sizeType: ['compressed']
        },
        littleImg: {
          name: '小图',
          type: 'littleImg',
          isSupport: true,
          supportSource: ['album', 'camera'],
          isCompress: true,
          maxDuration: 60,
          camera: 'back'
        },
        video: {
          name: '视频',
          type: 'video',
          isSupport: true,
          supportSource: ['album', 'camera'],
          isCompress: true,
          maxDuration: 60,
          camera: 'back'
        }
      }
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    showTitle:false,//是否展示标题
    demoSrc:'../../static/images/bac_jiahao.png',//默认图片
    initData:[],//页面数据变量
    fontArray:[{name:'小',value:"font-size:1rem;"},{name:'中',value:"font-size:1.5rem;"},{name:'大',value:"font-size:2rem;"}],//字体大小
    fontSuffix:0,//字体大小默认选中
    colorArray:[{name:'黑色',value:"color:black;"},{name:'红色',value:"color:red;"},{name:'蓝色',value:"color:blue;"},{name:'绿色',value:"color:green;"},],//字体颜色
    colorSuffix:0,//字体颜色默认选中
    fontWeight:'',//字体黑体
    weightState:false,//字体是否黑体
    fontCenter:'',//字体是否居中
    centerState:false,//居中状态
    //表对象
    attachment:{
      attTitle:'',//文本标题
      attValue:'',//文本内容
      attType:'',//类型
    },
    optType:''
  },

  lifetimes:{
  },
  /**
   * 组件的方法列表
   */
  methods: {

    init(type,id){
      if(id){
        this.getEditor(id)
      }
      if('footer' == type){
        this.setData({
          showTitle:true,
          'attachment.attType':'footer',
          optType:type
        })
      }
    },
    //获取要追加的内容id
    appendAffter(id){
      let that = this
      API_RichEditor.get(id).then(res => {
        if('footer' == res.attType){
          const appendItem = JSON.parse(res.attValue)
          for(var i = 0; i < appendItem.length; i++){
            that.data.initData.push(appendItem[i])
          }
          that.setData({initData:that.data.initData})
        }
      })
    },
    add(e){
      let that = this
      //根据传递类型新建对象
      let type = e.currentTarget.dataset.type
      let arr = this.data.initData
      switch (type) {
        case "text":
          arr.push(new item(
            type,
            null,
            that.data.fontArray,
            that.data.fontSuffix,
            that.data.colorArray,
            that.data.colorSuffix,
            that.data.fontWeight,
            that.data.weightState,
            that.data.fontCenter,
            that.data.centerState
          ))
          break
        case "bigImg":
          arr.push(new item(
            type,
            ''
          ))
          break
        case "video":
          arr.push(new item(
            type,
            ''
          ))
          break
        case "littleImg":
          arr.push(new item(
            type,
            []
          ))
      }
      this.setData({initData:arr})
    },
    //选择视频上传
    chooseVideo(e){
      let that = this
      let arr = this.data.initData
      let index = e.currentTarget.dataset.index
        wx.chooseMedia({
          count: 1,
          mediaType: ['video'],
          sourceType: that.properties.supportType.video.supportSource,
          success: function (res) {
            let item = arr[index]
            item.videoThumb = res.tempFiles[0].thumbTempFilePath
            item.value = res.tempFiles[0].tempFilePath
            console.log(res)
            API_Upload.upload(res.tempFiles[0].thumbTempFilePath,res=>{
              const {url} = JSON.parse(res.data)
              that.setData({initData: arr})
              that.data.initData[index].videoThumb = url
            },res=>{
                wx.showToast({
                    title:'上传失败',
                    icon:'none'
                })
            })
            API_Upload.upload(res.tempFiles[0].tempFilePath,res=>{
              const {url} = JSON.parse(res.data)
              that.setData({initData: arr})
              that.data.initData[index].value = url
            },res=>{
                wx.showToast({
                    title:'上传失败',
                    icon:'none'
                })
            })
          }
      })
    },
    changeTitle(e){
      this.setData({'attachment.attTitle': e.detail.value})
    },
    //输入内容
    changeInputValue(e){
      let that = this
      //获取是哪个元素要改变
      let index = e.currentTarget.dataset.index
      //获取选中的值进行更改
      that.data.initData[index].value =  e.detail.value
      this.setData({initData: that.data.initData})
    },
    //字号选择器
    fontPicker: function(e) {
      let that = this
      //获取是哪个元素要改变
      let index = e.currentTarget.dataset.index
      //获取选中的值进行更改
      that.data.initData[index].fontSuffix =  e.detail.value
      this.setData({initData: that.data.initData})
    },
    //颜色选择器
    colorPicker:function(e){
      let that = this
      //获取是哪个元素要改变
      let index = e.currentTarget.dataset.index
      //获取选中的值进行更改
      that.data.initData[index].colorSuffix =  e.detail.value
      this.setData({initData: that.data.initData})
    },
    //是否黑体加粗
    changeFontWeight(e){
      let that = this
      //获取是哪个元素要改变
      let index = e.currentTarget.dataset.index
      //获取选中的值进行更改
      that.data.initData[index].weightState =  !that.data.initData[index].weightState
      if(that.data.initData[index].weightState){
        that.data.initData[index].fontWeight = 'font-weight: bold;'
      }else{
        that.data.initData[index].fontWeight = ''
      }
      this.setData({
        initData: that.data.initData,
        weightState:that.data.initData[index].weightState
      })
    },
    //是否居中
    changeCenter(e){
      let that = this
      //获取是哪个元素要改变
      let index = e.currentTarget.dataset.index
      //获取选中的值进行更改
      that.data.initData[index].centerState =  !that.data.initData[index].centerState
      if(that.data.initData[index].centerState){
        that.data.initData[index].fontCenter = 'text-align: center;'
      }else{
        that.data.initData[index].fontCenter = ''
      }
      this.setData({
        initData: that.data.initData,
        centerState:that.data.initData[index].centerState
      })
    },
    
    //上传图片组件
    uploadBigImg(e){
      let that = this
      let index = e.currentTarget.dataset.index
      // 上传图片
      wx.chooseImage({
        count: 1,
        supportSource: that.properties.supportType.image.supportSource,
        sizeType: that.properties.supportType.image.sizeType,
        success: function(res) {
          that.setData({carPhotoStr:res.tempFilePaths[0]})
          var split = res.tempFilePaths[0].split('.')
          var last = split[split.length-1]
          if(last=='jpg' ||last=='png' ||last=='JPG' ||last=='PNG' ){
            API_Upload.upload(res.tempFilePaths[0],res=>{
              const {url} = JSON.parse(res.data)
              that.data.initData[index].value = url
              that.setData({
                initData: that.data.initData
              })
            },res=>{
                wx.showToast({
                    title:'上传失败',
                    icon:'none'
                })
            })
        }else{
          wx.showToast({
            title: '请上传jpg或png格式图片',
            icon:'none',
            duration:1500
          })
        }
        }
      })
    },
    uploadLittleImg(e){
      let that = this
      let index = e.currentTarget.dataset.index
      // 上传图片
      wx.chooseImage({
        count: 9,
        supportSource: that.properties.supportType.littleImg.supportSource,
        sizeType: that.properties.supportType.littleImg.sizeType,
        success: function(res) {
          //所选中的图片
          let tempArr = res.tempFilePaths
          for(var i = 0; i<tempArr.length; i++){
            var split = res.tempFilePaths[i].split('.')
            var last = split[split.length-1]
            if(last=='jpg' ||last=='png' ||last=='JPG' ||last=='PNG' ){
              API_Upload.upload(res.tempFilePaths[i],res=>{
                const {url} = JSON.parse(res.data)
                that.data.initData[index].value.push(url)
                that.setData({
                  initData: that.data.initData
                })
              },res=>{
                  wx.showToast({
                      title:'上传失败',
                      icon:'none'
                  })
              })
            }else{
              wx.showToast({
                title: '请上传jpg或png格式图片',
                icon:'none',
                duration:1500
              })
            }
          }
        }
      })
    },
    //过滤数组空值
    delNullValue(value){
      if(!value.type == 'bigImg'){
        return true
      }
      return value.value
    },
    //保存提交
    save(){
      let that = this
      //所有元素内arr
      var itemArr = that.data.initData.filter(this.delNullValue)
    
      console.log("editor")
      console.log(itemArr);
      that.data.attachment.attValue = JSON.stringify(itemArr)
      if(that.data.attachment.attType == 'footer'){
        if(!that.data.attachment.attTitle.trim()){
          wx.showToast({
            title: '请填写标题',
            icon:'none'
          })
          return
        }
      }
      
      console.log(that.data.attachment);
      if(that.data.attachment.id){
        API_RichEditor.edit(that.data.attachment).then(res=>{
          that.end()
        })
      }else{
        API_RichEditor.insert(that.data.attachment).then(res=>{
          that.setData({attachment:res})
          that.end()
        })
      }
    },
    end(){
      if(this.data.optType == 'footer'){
        this.footerBack()
      }else{
        this.attrBack()
        
      }
    },
    attrBack(){
      var data = {
        data: this.data.attachment
      }
      this.triggerEvent('GetAtt', data, {})
    },
    footerBack(){
      this.triggerEvent('EditorEvent', {}, {})
    },
    
    //获取指定内容
    getEditor(e){
      API_RichEditor.get(e).then(res => {
        const items = JSON.parse(res.attValue)
        this.setData({
          attachment:res,
          initData:items
        })
      })
    },
    moveUp(e){
      let that = this
      let index = e.currentTarget.dataset.index
      if(index==0){
        return
      }
      let arr = that.data.initData;
      [arr[index],arr[index-1]] = [arr[index-1],arr[index]];
      that.setData({initData:arr})
    },
    moveDown(e){
      let that = this
      let index = e.currentTarget.dataset.index
      let arr = that.data.initData;
      if(index == arr.length-1){
        return
      }
      [arr[index],arr[index+1]] = [arr[index+1],arr[index]];
      that.setData({initData:arr})
    },
    moveTop(e){
      let that = this
      let index = e.currentTarget.dataset.index
      if(index==0){
        return
      }
      let arr = that.data.initData;
      //置顶后依次向下
      arr.unshift(arr.splice(index , 1)[0]);
      //和头部进行位置交换
      // [arr[0],arr[index]] = [arr[index],arr[0]];
      that.setData({initData:arr})
    },
    del(e){
      let that = this
      wx.showModal({
        title:'删除',
        content:'是否删除此模块',
        success (res) {
          if (res.confirm) {
            const { index } = e.currentTarget.dataset
            that.data.initData.splice(index,1)
            that.setData({
              initData:that.data.initData
            })
          }
        }
      })
    },

  }
})
